<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="title" :width="drawerWidth" @ok="handleSubmit">
    <BasicForm @register="registerForm"></BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { editUserFormSchema } from '../data/data';
import { getUserInfo, userUpdate } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';

const { getIsMobile } = useAppInject();
const drawerWidth = ref('550px');
if (unref(getIsMobile)) {
  drawerWidth.value = '80%';
}
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 150,
  labelCol: { span: 4 },
  schemas: editUserFormSchema,
  showActionButtonGroup: false,
});

let title: any = ref('用户信息修改');
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  let record = data.record;
  let userId = record.userId;
  if (userId) {
    let userId = record.userId;
    let queryData = await getUserInfo({ userId: userId });
    if (queryData) {
      setFieldsValue({
        ...queryData,
      });
      return;
    }
  }
  let newData = { userId: record.userId };
  setFieldsValue({
    ...newData,
  });
});

async function handleSubmit() {
  try {
    const values = await validate();
    values['handlerName'] = 'appUserInfoUpdateHandler';
    setDrawerProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await userUpdate(values);
    }
    closeDrawer();
    emit('success', false);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
